#include "../../inc/skyFont.h"
#include "../../inc/skyUtils.h"
#ifdef _GLES_
namespace Sky
{
	Bool FontManager::createFont( String* fontName,i32 weight,i32 height,i32 width,Font* font )
	{
#ifdef _WIN_DX_

		//font->getFont().setHeight(height);
		//font->getFont().setWidth(width);
		//font->getFont().setWeight(weight);
		//font->getFont().trySelfCreate();
		//font->getFont().setFaceName(fontName->toCharString());
#elif defined(_WIN_)
		bool bRet = vFalse;
		static String m_curFontPath;
		do 
		{
			StringPtr	fontPath;
			HFONT       hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
			LOGFONTA    tNewFont = {0};
			LOGFONTA    tOldFont = {0};
			GetObject(hDefFont, sizeof(tNewFont), &tNewFont);
			if (fontName && fontName->toCharString())
			{	
				// create font from ttf file
				if (fontName->endWith(String(_XT(".TTF"))) || fontName->endWith(String(_XT(".ttf"))))
				{
					fontPath = Utils::fullPathFromRelativePath(*fontName);
					i32 nFindPos = fontName->rFind(String(_XT("/")));
					//fontName = nFindPos + 1;
					nFindPos = fontName->rFind(String(_XT(".")));
					fontPath = fontName->subStr(0,nFindPos);				
				}
				tNewFont.lfCharSet = DEFAULT_CHARSET;
				Memory::copy(tNewFont.lfFaceName, fontPath->toCharString(),LF_FACESIZE * sizeof(Char));
			}
			if (height)
			{
				tNewFont.lfHeight = -height;
			}
			GetObject(font->_hFont,  sizeof(tOldFont), &tOldFont);

			if (tOldFont.lfHeight == tNewFont.lfHeight
				&& ! strcpy(tOldFont.lfFaceName, tNewFont.lfFaceName))
			{
				// already has the font 
				bRet = true;
				break;
			}

			// delete old font
			if (font->_hFont != hDefFont)
			{
				DeleteObject(font->_hFont);
				// release old font register
				if (m_curFontPath.getLength() > 0)
				{
					if(::RemoveFontResource(m_curFontPath->toCharString()))
					{
						::SendMessage( vNull, WM_FONTCHANGE, 0, 0);
					}						
				}
				if(fontPath)
					m_curFontPath = *fontPath;
				else
					m_curFontPath.clear();
				// register temp font
				if (m_curFontPath.getLength() > 0)
				{
					if(::AddFontResource(m_curFontPath.toCharString()))
					{
						::SendMessage( vNull, WM_FONTCHANGE, 0, 0);
					}						
				}
			}
			font->_hFont = NULL;

			// create new font
			font->_hFont = CreateFontIndirectA(&tNewFont);
			if (!font->_hFont)
			{
				// create failed, use default font
				font->_hFont = hDefFont;
				break;
			}

			bRet = true;
		} while (0);
		return bRet;
#endif
		return vTrue;
	}
}
#endif
